﻿using Newtonsoft.Json;
using Shared.Method;
using Shared.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;

namespace WCFServer
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“Service1”。
    // 注意: 为了启动 WCF 测试客户端以测试此服务，请在解决方案资源管理器中选择 Service1.svc 或 Service1.svc.cs，然后开始调试。
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class TRService : IServiceTR
    {
        //public TRService()
        //{
        //    YcdMacBaseClass.Initialize();
        //    //LogHelper.WriteDebugLogTxt("初始化", "初始化后台MAC分配系统");
        //}

        private readonly Dictionary<int, string> GRANTKEY = new Dictionary<int, string>()
        {
            {1,"TDQ7ss*Qp787eb?" },
            {2,"(schhkKJNN233>119ebN" },
            {3,"RssPmq&AwYcc7<98Bux" }
        };

        /// <summary>
        /// 接口判定
        /// </summary>
        /// <param name="keyCode">验证码</param>
        /// <param name="value">传入参数</param>
        /// <param name="grade">接口权限等级，1为查询等级；2为读写等级；3为管理员等级</param>
        /// <returns></returns>
        private bool CheckCode(string value, int grade = 1)
        {
            try
            {
                if (string.IsNullOrEmpty(value))
                {
                    return false;
                }
                int index = OperationContext.Current.IncomingMessageHeaders.FindHeader("header", "CheckCode");
                if (index == -1) return false;
                string code = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>(index);

                //判断需要的等级
                var keylist = (from k in GRANTKEY
                               where k.Key >= grade
                               select k.Value).ToList();

                if (keylist == null || keylist.Count == 0) return false;

                //判断校验码是否正确
                for (int i = 0; i < keylist.Count; i++)
                {
                    if (Encrypt.GetCheckCode(keylist[i], value) == code)
                        return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 泛型通用型查询方法，返回ResultSet<List<T>>转换成的字符串
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="value">参数</param>
        /// <returns></returns>
        private string Select<T>(string value) where T : TableBase, new()
        {
            ResultSet<List<T>> ret = new ResultSet<List<T>>();
            if (string.IsNullOrEmpty(value) || CheckCode(value) == false)
            {
                ret.Error("传入参数为空");
                return JsonConvert.SerializeObject(ret);
            }
            try
            {
                T whereData = JsonConvert.DeserializeObject<T>(value);

                List<T> selectRes = DBAccess.SelectData(whereData);
                if (selectRes == null || selectRes.Count == 0)
                    ret.Error("查询失败，没有结果");
                else
                {
                    ret.Success("查询成功", selectRes);
                }
            }
            catch (Exception ex)
            {
                ret.Error(ex.Message);
            }
            return JsonConvert.SerializeObject(ret);
        }

        /// <summary>
        /// 查询数量的泛型方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns>返回符合条件的数据条数</returns>
        private string SelectCount<T>(string value) where T : TableBase
        {
            ResultSet ret = new ResultSet();
            if (string.IsNullOrEmpty(value)|| CheckCode(value) == false)
            {
                ret.Error("传入参数为空");
                return JsonConvert.SerializeObject(ret);
            }
            try
            {
                T whereData = JsonConvert.DeserializeObject<T>(value);
                int selectRes = DBAccess.SelectCount(whereData);
                ret.Success(selectRes.ToString());
            }
            catch (Exception ex)
            {
                ret.Error(ex.Message);
            }
            return JsonConvert.SerializeObject(ret);
        }
        /// <summary>
        /// 泛型更新方法，返回更新成功或者失败的信息
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="value">数据值</param>
        /// <returns></returns>
        private string Update<T>(string value) where T : TableBase
        {
            ResultSet ret = new ResultSet();
            if (string.IsNullOrEmpty(value) || CheckCode(value,2) == false)
            {
                ret.Error("传入参数为空");
                return JsonConvert.SerializeObject(ret);
            }
            try
            {
                T data = JsonConvert.DeserializeObject<T>(value);
                if (DBAccess.UpdateData(data) >= 1)
                    ret.Success("更新成功");
                else
                    ret.Error("更新失败");
            }
            catch (Exception ex)
            {
                ret.Error(ex.Message);
            }
            return JsonConvert.SerializeObject(ret);
        }

        private string Delete<T>(string value) where T : TableBase
        {
            ResultSet ret = new ResultSet();
            if (string.IsNullOrEmpty(value) || CheckCode(value,2) == false)
            {
                ret.Error("传入参数为空");
                return JsonConvert.SerializeObject(ret);
            }
            try
            {
                T data = JsonConvert.DeserializeObject<T>(value);
                int count = DBAccess.DeleteData(data);
                ret.Success(count.ToString());
            }
            catch (Exception ex)
            {
                ret.Error(ex.Message);
            }
            return JsonConvert.SerializeObject(ret);
        }
        /// <summary>
        /// 泛型插入方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        private string Insert<T>(string value) where T : TableBase
        {
            ResultSet ret = new ResultSet();
            if (string.IsNullOrEmpty(value) || CheckCode(value,2) == false)
            {
                ret.Error("传入参数为空");
                return JsonConvert.SerializeObject(ret);
            }
            try
            {
                T data = JsonConvert.DeserializeObject<T>(value);
                long insertRes = DBAccess.InsertDataIdentify(data);//能否返回插入ID的代码块_ADD_11.6
                ret.Success(insertRes.ToString());
            }
            catch (Exception ex)
            {
                ret.Error(ex.Message);//失败返回错误代码
            }
            return JsonConvert.SerializeObject(ret);
        }

        /// <summary>
        /// 写入测试数据
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string InsertTestTop(string value)
        {
            //test
            //return DBAccess.SelectCountAll<WORKER>().ToString();
            //WORKER where = new WORKER();
            //where.SetWhere();
            //where.SEX = "女";
            //return DBAccess.SelectCount(where).ToString();
            //DBAccess.SelectAll<WORKER>();
            return Insert<TEST_TOP>(value);
        }

        /// <summary>
        /// 查询最后结果
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectTestTop(string value)
        {
            return Select<TEST_TOP>(value);
        }
        /// <summary>
        /// 查询结果
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        //public string SelectTestSecond(string value)
        //{
        //    return Select<TEST_SECOND>(value);
        //}

        //判断是否能够做接下来的工序
        public string CanStart(string value)
        {
            //逻辑如下，获取测试端信息；
            //①获取当前产品的的MAC地址，获得电脑的MAC地址/SN/标志
            //②通过MAC获得工位STATION信息和产品信息PRODUCT
            //③判断流程顺序、工序顺序、产线、工位、测试结果等是否符合要求（策略要求灵活）
            //④返回能否测试的判定条件
            //⑤修改产品表状态，设置为正在测试当中，返回能否测试的结果

            ResultSet ret = new ResultSet();
            if (string.IsNullOrEmpty(value) || CheckCode(value) == false)
            {
                ret.Error("传入参数为空");
                return JsonConvert.SerializeObject(ret);
            }

            try
            {
                StartRequest testReq = JsonConvert.DeserializeObject<StartRequest>(value);
                //通过MAC/SN/标志获得产品信息；通过MAC获得工位信息

                #region 查询产品信息
                PRODUCT proWhere = new PRODUCT();//设置产线产品的查询条件
                proWhere.SetWhere();//设置接下来的赋值为条件
                if (string.IsNullOrEmpty(testReq.PRODUCT_MAC) == false)//通过MAC查询产品信息
                {
                    if(testReq.PRODUCT_MAC.ToUpper().StartsWith(SharedData.YCD_MAC_EPON_START) || testReq.PRODUCT_MAC.ToUpper().StartsWith(SharedData.YCD_MAC_GPON_START))
                    {
                        proWhere.YCD_MAC = testReq.PRODUCT_MAC;
                    }
                    else
                    {
                        proWhere.MAC = testReq.PRODUCT_MAC;
                    }
                }
                else if (string.IsNullOrEmpty(testReq.PRODUCT_SN) == false)//通过SN查询产品信息
                {
                    //proWhere.SN = testReq.PRODUCT_SN;
                    //通过SN查找到对应的MAC
                    proWhere.SetWhere(string.Format("MAC=(select MACAddr from Modem.dbo.Device_Data where SN='{0}')",testReq.PRODUCT_SN));
                }
                else
                {
                    ret.Error("未能获得SN/MAC");
                    return JsonConvert.SerializeObject(ret);
                }
                List<PRODUCT> product = DBAccess.SelectData(proWhere);
                #endregion

                #region 产品信息数量判断
                if (product == null || product.Count == 0)
                {
                    ret.Error("没有查询到产品信息");
                    return JsonConvert.SerializeObject(ret);
                }

                if (product.Count > 1)
                {
                    ret.Error("有多条相同的产品信息，请检查MAC/SN/产品标识是否唯一");
                    return JsonConvert.SerializeObject(ret);
                }

                //判断break_state如果为true，则产品锁定，删除此判断语句
                //if (product[0].BREAK_STATE == true)
                //{
                //    ret.Error("MAC地址已经锁定，请联系组长解锁");
                //    return JsonConvert.SerializeObject(ret);
                //}


                #endregion

                #region  获得工位信息

                if (string.IsNullOrEmpty(testReq.STATION_MAC))
                {
                    ret.Error("未能获得工位电脑的MAC地址");
                    return JsonConvert.SerializeObject(ret);
                }

                STATION staWhere = new STATION();
                staWhere.SetWhere();
                staWhere.MAC = testReq.STATION_MAC;

                List<STATION> station = DBAccess.SelectData(staWhere);
                if (station == null || station.Count == 0)
                {
                    ret.Error("未能获得工位信息");
                    return JsonConvert.SerializeObject(ret);
                }

                if (station.Count > 1)
                {
                    ret.Error("有两个相同MAC地址的工位，请检查");
                    return JsonConvert.SerializeObject(ret);
                }
                #endregion

                #region 判断产品能否测试或生产
                //判断方法
                //①流程->②工序+产线->③测试结果

                //第一个判定条件->上一个工序必须结束才可以进行下一个工序，产品上的工序与当前工序不同
                if (product[0].NODE_STATE == false && product[0].NODE_ID != station[0].NODE_ID)
                {
                    //上一个工序的状态为正在进行，不能直接进入下一个状态，FALSE标识开始；TRUE标识结束
                    ret.Error("上一个工序并未完成，不能进行此工序，工序ID为：" + product[0].NODE_ID);
                    return JsonConvert.SerializeObject(ret);
                }

                //查询上一个工序的信息
                //判断工序顺序,获得现在的工序
                NODE nodeWhere = new NODE();
                nodeWhere.SetWhere();
                ////当前工序


                //之前工序
                nodeWhere.ID = (long)product[0].NODE_ID;
                List<NODE> beforeNode = DBAccess.SelectData(nodeWhere);
                if (beforeNode == null || beforeNode.Count != 1)
                {
                    ret.Error("之前的工序不存在，请联系管理员重新配置工序编码，工序ID为：" + product[0].NODE_ID);
                    return JsonConvert.SerializeObject(ret);
                }

                //获得之前流程
                FLOW flowWhere = new FLOW();

                flowWhere.SetWhere();
                flowWhere.ID = (long)product[0].FLOW_ID;
                var flowBefore = DBAccess.SelectData(flowWhere);
                if (flowBefore == null || flowBefore.Count != 1)
                {
                    ret.Error("当前流程不存在，请联系管理员，流程ID为：" + product[0].FLOW_ID);
                    return JsonConvert.SerializeObject(ret);
                }
                //获得当前流程
                flowWhere.ID = (long)station[0].FLOW_ID;
                var flowMy = DBAccess.SelectData(flowWhere);
                if (flowMy == null || flowMy.Count != 1)
                {
                    ret.Error("之前流程不存在，请联系管理员，流程ID为：" + station[0].FLOW_ID);
                    return JsonConvert.SerializeObject(ret);
                }

                //简化的判断方案
                //只有三种情况可以通过--①result==false;error_id=node_id；②result=true;line==line;next_id=node_id;③result=true;line!=line;
                //增加一个可能性--测试结果为不通过或通过，可以更改
                if (product[0].NODE_ID == station[0].NODE_ID && product[0].FLOW_ID == station[0].FLOW_ID)
                {
                    //工序不变，产线不变（流程不变），可以再次上传数据
                    ret.Success("此工序可以进行");
                }
                else if (product[0].TEST_RESULT == "N" && beforeNode[0].ERROR_ID == station[0].NODE_ID)
                {
                    //结果错误，错误ID与当前工序ID相同
                    ret.Success("此工序可以进行");
                } else if (product[0].TEST_RESULT == "Y" && product[0].FLOW_ID == station[0].FLOW_ID && beforeNode[0].NEXT_ID == station[0].NODE_ID)
                {
                    //结果正确，产线相同（流程相同），之前工序的NEXT_ID与当前工序相同
                    ret.Success("此工序可以进行");
                } else if (product[0].TEST_RESULT == "Y" && flowBefore[0].SORT < flowMy[0].SORT && flowBefore[0].NODE_END == product[0].NODE_ID && flowMy[0].NODE_START == station[0].NODE_ID)
                {
                    //结果正确，流程不同，之前流程是当前流程之前的流程；之前工序为之前流程最后一个工序；当前工序为当前流程开始工序；
                    ret.Success("此工序可以进行");
                }
                else
                {
                    ret.Error(string.Format("此工序不可进行，MAC：{0}\n产品上个工序为：{1}，产线为：{2}",
                        testReq.PRODUCT_MAC,
                        beforeNode[0].NAME,
                        product[0].LINE_ID
                        ));
                }

                //返回结果信息
                return JsonConvert.SerializeObject(ret);

                #endregion

            }
            catch (Exception ex)
            {
                ret.Error(ex.Message);
            }

            return JsonConvert.SerializeObject(ret);
        }

        //写工位的信息的接口
        public string InsertStation(string value)
        {
            return Insert<STATION>(value);
        }
        /// <summary>
        /// 查询工位信息是否存在
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectStationCount(string value)
        {
            return SelectCount<STATION>(value);
        }
        /// <summary>
        /// 查询工位信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectStation(string value)
        {
            return Select<STATION>(value);
        }

        /// <summary>
        /// 更新工位信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string UpdateStation(string value)
        {
            return Update<STATION>(value);
        }
        /// <summary>
        /// 查询产线信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectLine(string value)
        {
            return Select<LINE>(value);
        }
        /// <summary>
        /// 查询工序信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectNode(string value)
        {
            return Select<NODE>(value);
        }

        /// <summary>
        /// 插入工序信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string InsertNode(string value)
        {
            return Insert<NODE>(value);
        }

        /// <summary>
        /// 查询工序数量
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectNodeCount(string value)
        {
            return SelectCount<NODE>(value);
        }

        /// <summary>
        /// 更新工序信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string UpdateNode(string value)
        {
            return Update<NODE>(value);
        }
        /// <summary>
        /// 删除工序节点
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string DeleteNode(string value)
        {
            return Delete<NODE>(value);
        }

        /// <summary>
        /// 查询员工信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectWorker(string value)
        {
            return Select<WORKER>(value);
        }
        /// <summary>
        /// 修改产品状态
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string UpdateProduct(string value)
        {
            //增加判定是否最后一个工序的方法，并更新一下product表
            IsLastNode(value);
            return Update<PRODUCT>(value);
        }

        /// <summary>
        /// 写入产品信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string InsertProduct(string value)
        {
            if (CanInsertProduct(value))
            {
                return Insert<PRODUCT>(value);
            }
            else
            {
                ResultSet ret = new ResultSet();
                ret.Error("不是首道工序，不能写产品数据");
                return JsonConvert.SerializeObject(ret);
            }
        }
        /// <summary>
        /// 获得MAC产品的数量
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectProductCount(string value)
        {
            return SelectCount<PRODUCT>(value);
        }
        /// <summary>
        /// 获得产品信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectProduct(string value)
        {
            return Select<PRODUCT>(value);
        }

        /// <summary>
        /// 写入数据到过程表
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string InsertProcess(string value)
        {
            return Insert<PROCESS>(value);
        }
        /// <summary>
        /// 查询过程表
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectProcess(string value)
        {
            return Select<PROCESS>(value);
        }

       public string  SelectProcessCount(string value)
        {
            return SelectCount<PROCESS>(value);
        }

        /// <summary>
        /// 查询装盒表
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectBoxModem(string value)
        {
            return Select<BOX_MODEM>(value);
        }

        /// <summary>
        /// 查询某条件下盒子已经入盒子的数量
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectBoxModemCount(string value)
        {
            return SelectCount<BOX_MODEM>(value);
        }

        /// <summary>
        /// 写入装盒信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string InsertBoxModem(string value)
        {
            return Insert<BOX_MODEM>(value);
        }

        /// <summary>
        /// 更新装盒信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string UpdateBoxModem(string value)
        {
            return Update<BOX_MODEM>(value);
        }
        /// <summary>
        /// 查询数据表数据
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectDeviceData(string value)
        {
            return Select<Device_Data>(value);
        }
        /// <summary>
        /// 查询数据表中某数据数量
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectDeviceDataCount(string value)
        {
            return SelectCount<Device_Data>(value);
        }
        /// <summary>
        /// 更新SN号码
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string UpdateDeviceData(string value)
        {
            return Update<Device_Data>(value);
        }

        public string InsertDeviceData(string value)
        {
            return Insert<Device_Data>(value);
        }
        /// <summary>
        /// 查询流程集合
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectFlowGroup(string value)
        {
            return Select<FLOW_GROUP>(value);
        }
        /// <summary>
        /// 插入流程集合数据
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string InsertFlowGroup(string value)
        {
            return Insert<FLOW_GROUP>(value);
        }
        /// <summary>
        /// 更新流程集合
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string UpdateFlowGroup(string value)
        {
            return Update<FLOW_GROUP>(value);
        }

        /// <summary>
        /// 查询流程集合的数量
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectFlowGroupCount(string value)
        {
            return SelectCount<FLOW_GROUP>(value);
        }

        /// <summary>
        /// 查询流程
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectFlow(string value)
        {
            return Select<FLOW>(value);
        }
        /// <summary>
        /// 插入流程数据
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string InsertFlow(string value)
        {
            return Insert<FLOW>(value);
        }
        /// <summary>
        /// 更新流程
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string UpdateFlow(string value)
        {
            return Update<FLOW>(value);
        }

        /// <summary>
        /// 查询流程的数量
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SelectFlowCount(string value)
        {
            return SelectCount<FLOW>(value);
        }

        public string UpdateLine(string value)
        {
            return Update<LINE>(value);
        }

        public string InsertLine(string value)
        {
            return Insert<LINE>(value);
        }

        public string SelectCountLine(string value)
        {
            return SelectCount<LINE>(value);
        }

        public string SelectCountWorker(string value)
        {
            return Select<WORKER>(value);
        }

        public string InsertWorker(string value)
        {
            return Insert<WORKER>(value);
        }

        public string UpdateWorker(string value)
        {
            return Update<WORKER>(value);
        }

        public string SelectSoftware(string value)
        {
            return Select<SOFTWARE>(value);
        }

        public string SelectDeviceType(string value)
        {
            return Select<Device_Type>(value);
        }


        public string UpdateDeviceType(string value)
        {
            return Update<Device_Type>(value);
        }


        public string InsertDeviceType(string value)
        {
            return Insert<Device_Type>(value);
        }


        public string SelectBosaData(string value)
        {
            return Select<BOSA_DATA>(value);
        }


        public string SelectBosaDataCount(string value)
        {
            return SelectCount<BOSA_DATA>(value);
        }


        public string UpdateBosaData(string value)
        {
            return Update<BOSA_DATA>(value);
        }

        public string InsertBosaData(string value)
        {
            return Insert<BOSA_DATA>(value);
        }

        public string SelectProvince(string value)
        {
            return Select<PROVINCE>(value);
        }

        //public  string SelectViewSnList(string value)
        //{
        //    return Select<View_SnList>(value);
        //}

        public string SelectProductCountData(string value)
        {
            return Select<PRODUCT_COUNT_DATA>(value);
        }

        public string SelectProductCountDataCount(string value)
        {
            return SelectCount<PRODUCT_COUNT_DATA>(value);
        }

        public string InsertYcdDevice(string value)
        {
            return Insert<YCD_DEVICE>(value);
        }

        public string UpdateYcdDevice(string value)
        {
            return Update<YCD_DEVICE>(value);
        }

        public string SelectYcdDevice(string value)
        {
            return Select<YCD_DEVICE>(value);
        }

        public string SelectYcdDeviceCount(string value)
        {
            return SelectCount<YCD_DEVICE>(value);
        }

        public string SelectOrder(string value)
        {
            return Select<YCD_ORDER>(value);
        }
        public string SelectOrderCount(string value)
        {
            return SelectCount<YCD_ORDER>(value);
        }
        public string UpdateOrder(string value)
        {
            return Update<YCD_ORDER>(value);
        }
        public string InsertOrder(string value)
        {
            return Insert<YCD_ORDER>(value);
        }
        public string SelectProductSn(string value)
        {
            return Select<PRODUCT_SN>(value);
        }
        public string SelectProductSnCount(string value)
        {
            return SelectCount<PRODUCT_SN>(value);
        }
        public string UpdateProductSn(string value)
        {
            return Update<PRODUCT_SN>(value);
        }

        public string SelectProductSnLog(string value)
        {
            return Select<PRODUCT_SN_LOG>(value);
        }

        public string SelectProductSnLogCount(string value)
        {
            return SelectCount<PRODUCT_SN_LOG>(value);
        }

        public string SelectPacking(string value)
        {
            return Select<PACKING>(value);
        }

        public string SelectPackingCount(string value)
        {
            return SelectCount<PACKING>(value);
        }
        public string UpdatePacking(string value)
        {
            return Update<PACKING>(value);
        }

        public string InsertPacking(string value)
        {
            return Insert<PACKING>(value);
        }

        //获取MAC地址
        public string GetYcdMac(string value)
        {
            try
            {
                if (CheckCode(value, 2) == false) throw new Exception("授权验证失败");

                return DBAccess.GetYcdMac(value);
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("GetYcdMac", "执行错误", ex.ToString());
                return null;
            }
            //string sql = string.Format(" DECLARE	@ycd_mac varchar(20),@message varchar(200)   EXEC	[dbo].[Proc_GetYcdMac] 	@pon_type = N'{0}',@ycd_mac = @ycd_mac OUTPUT,@message = @message OUTPUT 	 select @ycd_mac",value);

            //return DBAccess.ExecuteGetReturn<string>(sql, "YCD_DEVICE");
        }

        //执行存储过程或SQL语句
        public int ExecuteSQL(string value)
        {
            try
            {
                if (CheckCode(value, 3) == false) throw new Exception("授权验证失败");

                if (value.Contains("TEST_TOP") ||
                    value.Contains("PACKING"))
                {
                    return DBAccess.ExecuteNonQuery<TEST_TOP>(value);
                }

                if (
                   value.Contains("BOSA_DATA") ||
                   value.Contains("Device_Data") ||
                   value.Contains("Device_Type") ||
                   value.Contains("YCD_DEVICE") ||
                   value.Contains("BOB_DEFAULT") ||
                   value.Contains("BOB_TYPE") ||
                   value.Contains("BOB_DATA")
                  )
                {
                    return DBAccess.ExecuteNonQuery<Device_Data>(value);
                }

                return DBAccess.ExecuteNonQuery<PRODUCT>(value);
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("ExecuteSQL", "执行SQL语句错误", ex.ToString());
                return -1;
            }
        }

        /// <summary>
        /// 执行SQL语句获取返回
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string ExecuteReturnSQL(string value)
        {
            try
            {
                if (CheckCode(value, 2) == false) throw new Exception("授权验证失败");

                if (value.Contains("TEST_TOP") ||
                    value.Contains("PACKING"))
                {
                    return DBAccess.ExecuteGetReturn<string>(value, "TEST_TOP");
                }

                if (
                   value.Contains("BOSA_DATA") ||
                   value.Contains("Device_Data") ||
                   value.Contains("Device_Type") ||
                   value.Contains("YCD_DEVICE")||
                   value.Contains("BOB_DEFAULT") ||
                   value.Contains("BOB_TYPE") ||
                   value.Contains("BOB_DATA")
                  )
                {
                    return DBAccess.ExecuteGetReturn<string>(value, "Device_Data");
                }


                return DBAccess.ExecuteGetReturn<string>(value,"PRODUCT");
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("ExecuteReturnSQL", "执行SQL语句错误", ex.ToString());
                return "";
            }
        }

        public string SelectJson(string value)
        {
            try
            {
                if (CheckCode(value, 2) == false) throw new Exception("授权验证失败");

                if (value.Contains("TEST_TOP") ||
                    value.Contains("PACKING"))
                {
                    return DBAccess.SelectDataJson(value, "TEST_TOP");
                }

                if (
                   value.Contains("BOSA_DATA") ||
                   value.Contains("Device_Data") ||
                   value.Contains("Device_Type") ||
                   value.Contains("YCD_DEVICE")||
                   value.Contains("BOB_DEFAULT")||
                   value.Contains("BOB_TYPE") ||
                   value.Contains("BOB_DATA")
                  )
                {
                    return DBAccess.SelectDataJson(value, "Device_Data");
                }


                return DBAccess.SelectDataJson(value, "PRODUCT");
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogTxt("SelectJson", value, ex.ToString());
                return "";
            }
        }

        /// <summary>
        /// 能否写产品信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private bool CanInsertProduct(string value)
        {
            PRODUCT pro = JsonConvert.DeserializeObject<PRODUCT>(value);
            if (pro.FLOW_ID == null) return false;
            FLOW minFlow = DBAccess.GetFlowIdFromMinSort(pro.FLOW_ID.Value);

            if (minFlow!=null
                &&pro.FLOW_ID == minFlow.ID 
                && pro.NODE_ID == minFlow.NODE_START)//查找最小的工序节点，如果产品上的信息与之匹配则可以插入数据
                return true;
            else
                return false;
        }

        /// <summary>
        /// 如果时最后一道工序，并且结果时正确的时候，产品生产完成；将产品完工这个工序安排到手工完成？
        /// </summary>
        /// <param name="value"></param>
        private void IsLastNode(string value)
        {
            try
            {
                PRODUCT pro = JsonConvert.DeserializeObject<PRODUCT>(value);//产品
                if (pro.FLOW_ID == null) return;//当flow_ID为空时不执行此操作
                FLOW maxFlow = DBAccess.GetFlowIdFromMaxSort(pro.FLOW_ID.Value);

                //if (maxFlow == null) return;
                //if (maxFlow.ID != pro.FLOW_ID) return;
                //if (maxFlow.NODE_END != pro.NODE_ID) return;
                //if (pro.TEST_RESULT != "Y") return;

                if (maxFlow != null
                    && pro.FLOW_ID == maxFlow.ID//流程为最后流程
                    && pro.NODE_ID == maxFlow.NODE_END//工序为最后工序
                    && pro.TEST_RESULT == "Y")//测试结果为正确
                {
                    pro.Clear();
                    pro.SetWhere();
                    pro.MAC = pro.MAC;

                    pro.SetUpdate();
                    pro.STATE = true;//更新为产品生产完成
                    pro.END_TIME = DateTime.Now;
                    //得到所有的过程表ID信息，保存到PROCESS_ALL
                    //pro.PROCESS_ALL = DBAccess.GetProcessAll(pro.MAC);

                    DBAccess.UpdateData(pro);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("写完成工序失败，错误信息为：{0}", ex.Message));
            }
        }
    }
}
